package com.dzqc.fly.controller.mobile;

import cn.hutool.json.JSONException;
import cn.hutool.json.JSONObject;
import com.dzqc.fly.common.IpUtils;
import com.dzqc.fly.common.Result;
import com.dzqc.fly.common.StringUtil;
import com.dzqc.fly.db.pojo.AppFilePojo;
import com.dzqc.fly.service.FileUploadService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.UUID;

@RestController
@RequestMapping("/file")
@Tag(name = "MobileUploadController", description = "APP首页文件上传")
@Slf4j
@EnableAutoConfiguration
public class MobileUploadController {

    @Value("${file.upload.dir}")
    private String uploadFilePath;

    @Autowired
    private FileUploadService fileUploadService;


    @PostMapping("/uploadMultipleFiles")
    @Operation(summary = "手机端文件上传接口")
    public String fileUpload(@RequestParam("files") MultipartFile file, HttpServletRequest request) throws JSONException {
        JSONObject result = new JSONObject();
        if (file.isEmpty()) {
            result.put("error", "空文件!");
            return result.toString();
        }
        // 文件名
        String fileName = file.getOriginalFilename();
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        String fileNewName= (UUID.randomUUID().toString().replaceAll("-",""))+suffixName;
        log.info("上传文件名称为:{}, 后缀名为:{}!", fileName, suffixName);
        String size= StringUtil.convertToString(file.getSize()/1024)+"kb";
        File fileDir = new File(uploadFilePath);
        System.out.println(fileDir.getAbsolutePath());
        // 检测目录是否存在
        if (!fileDir.getParentFile().exists()) {
            fileDir.getParentFile().mkdirs();
        }
        try {
            File newFile = new File(fileDir.getAbsolutePath() + File.separator + fileNewName);
            file.transferTo(newFile);
        } catch (Exception e) {
            log.error("发生错误: {}", e);
            result.put("error", e.getMessage());
            return result.toString();
        }
        AppFilePojo app=new AppFilePojo();
        app.setOriginalname(fileName);
        app.setTargetname(fileNewName);
        app.setIp(IpUtils.getHostIp());
        app.setPath(fileDir.getAbsolutePath() + File.separator + fileName);
        app.setSize(size);
        app.setCreattime( new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        fileUploadService.insert(app);
        result.put("success", "文件上传成功!");
        return result.toString();
    }

    /**
     * 多个文件上传
     *
     * @param files
     * @return
     * @throws JSONException
     */
    @ResponseBody
    @PostMapping("/uploadFiles")
    @Operation(summary = "手机端多文件上传接口")
    public Result fileUploads(String name, @RequestParam("files") MultipartFile files[]) throws JSONException {

        for (int i = 0; i < files.length; i++) {
            String fileName = files[i].getOriginalFilename();
            File dest = new File(uploadFilePath + '/' + fileName);
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            try {
                files[i].transferTo(dest);
            } catch (Exception e) {
                log.error("发生错误: {}", e);
                Result result=Result.error();
                return  result;

            }
        }
        Result result=Result.ok().put("message","文件上传成功!");
        return result;
    }

   // 首页图片显示
   @GetMapping("/getAppIndexImg")
   @Operation(summary = "获取APP首页图片接口")
    public  Result getAppIndexImg(){

       HashMap hashMap = fileUploadService.searchimgIndex();
       if (hashMap !=null) {
           Result result=Result.ok();
           String targetname = hashMap.get("targetname").toString();
           String ip=hashMap.get("ip").toString();
          // String path=ip+":8080/upload/"+name;
           String path="/upload/"+targetname;
           result.put("path",path);
           return result;
       }
       Result result=Result.error();
       return  result;

    }

}
